/*
 * Copyright (c) 2014. Lincong All rights reserved.
 * Mail lincong1987@gmail.com
 * QQ 159257119
 * This software is the confidential and proprietary information of Lincong,
 * You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with Lincong.
 * $Id$
 */

define(function (require, exports, module) {

    var Model = require("Firebird.Model");

    /**
     * 服务基类
     * @class Firebird.Service
     * @extends Firebird.Model
     * @see  Firebird.Model
     */
    Firebird.define("Firebird.Service", {
        extend: "Firebird.Model",
        config: {
            controller: "",
            mapping: {
                // 数据接口
                index: "/index/{0}/{1}",
                get: "/get/{0}",
                put: "/put",
                post: "/post",
                "delete": "/delete/{0}",
                // view 方法
                save: "/save",
                edit: "/edit/{0}",
                view: "/view/{0}"
            }
        },
        constructor: function (config) {
            this.initConfig(config);
        },
        buildRequest: function (url) {
            url = url.replace(/\{contextPath\}/, firebird.api.get("contextPath") || "");
            var uuid = this.getUUID();
            return {
                uuid: uuid,
                url: Firebird.String.urlAppend(url, "FBID=" + uuid)
            };
        },
        getAction: function (name, filter) {
            filter = filter || function(a){return a};
            var mapping = this.getMapping()[name] || "";
            return this.buildRequest(this.getController().replace(/\{contextPath\}/, firebird.api.get("contextPath") || "") + filter(mapping)).url;
        },
        request: function (url, options, callback) {
            return $.ajax($.extend({}, {
                    url: this.buildRequest(url),
                    dataType: "json",
                    success: function (data) {
                        callback(data);
                    },
                    error: function (jqXHR, textStatus, e) {
                        top.$.dialog.error("查询数据失败。", {});
                    }
                },
                options));
        },
        /**
         * 插入数据
         * @param data
         * @param options
         * @param callback
         * @returns {*}
         */
        insert: function (data, options, callback) {
            return $.ajax($.extend({}, {
                    url: this.getAction("post"),
                    dataType: "json",
                    type: "post",
                    data: data,
                    success: function (data) {
                        callback(data);
                    },
                    error: function (jqXHR, textStatus, e) {
                        top.$.dialog.error("插入数据失败。", {});
                    }
                },
                options || {}));
        },
        modify: function (data, options, callback) {
            return $.ajax($.extend({}, {
                    url: this.getAction("put"),
                    dataType: "json",
                    type: "post",
                    data: data,
                    success: callback,
                    error: function (jqXHR, textStatus, e) {
                        top.$.dialog.error("修改数据失败。", {});
                    }
                },
                options));
        },
        remove: function (ids, options, callback) {
            if (firebird.isArray(ids)) {
                ids = Firebird.Array.pluck(ids, "id").join(",");
            }
            return $.ajax($.extend({}, {
                    url: this.getAction("delete", function(url){
                        return Firebird.String.format(url, ids);
                    }),
                    dataType: "json",
                    success: callback,
                    error: function (jqXHR, textStatus, e) {
                        top.$.dialog.error("删除数据失败。", {});
                    }
                },
                options));
        },
        select: function (id, options, callback) {
            return $.ajax($.extend({}, {
                    url: this.buildRequest(this.getRequestMapping().controller + Firebird.String.format(this.getMapping().get, id)),
                    dataType: "json",
                    success: callback,
                    error: function () {
                        $.dialog.error("获取数据失败。", {});
                    }
                },
                options));
        },
        selectList: function (page, size, options, callback) {
            return $.ajax($.extend({}, {
                    url: this.buildRequest(this.Controller() + Firebird.String.format(this.getMapping().index, page, size)),
                    dataType: "json",
                    success: callback,
                    error: function () {
                        top.$.dialog.error("获取数据失败。", {});
                    }
                },
                options));
        },
        ready: function () {
            firebird.sandbox.run(function () {
                firebird.api.get("top.layout").cells("c").progressOff();
            });
        },
        close: function (data) {
            var dialog = top.$.dialog.get(window);
            dialog.close(data);
            dialog.remove();
        },
        setButtons: function (buttons) {
            var dialog = top.$.dialog.get(window);
            dialog.button(buttons);
        },
        getUUID: function () {
            return "__FBID__" + new Date().getTime();
        },
        save: function (options, callback) {
            var req = this.buildRequest(this.getController() + this.getMapping().save);
            var url = req.url;
            if (options.data) {
                firebird.data.set(req.uuid, options.data);
            }
            var dialog = top.$.dialog.open(url, $.extend({}, {
                    id: req.uuid,
                    onclose: function () {
                        if (callback) {
                            callback(dialog.returnValue);
                        } else {
                            if (dialog.returnValue && dialog.returnValue.success === true) {
                                top.$.dialog.tips("数据添加成功！", 3000);
                            }
                        }
                    }
                },
                options));
            return dialog;
        },
        edit: function (id, options, callback) {
            var req = this.buildRequest(this.getController() + Firebird.String.format(this.getMapping().edit, id));
            var url = req.url;
            if (options.data) {
                firebird.data.set(req.uuid, options.data);
            }
            var dialog = top.$.dialog.open(url, $.extend({}, {
                    id: req.uuid,
                    onclose: function () {
                        if (callback) {
                            callback(dialog.returnValue);
                        } else {
                            if (dialog.returnValue && dialog.returnValue.success === true) {
                                top.$.dialog.tips("数据修改成功！", 3000);
                            }
                        }
                    }
                },
                options));
            return dialog;
        },
        view: function (options) {
            var req = this.buildRequest(this.getController() + this.getMapping().view);
            var url = req.url;
            return top.$.dialog.open(url, $.extend({}, {
                    id: req.uuid
                },
                options));
        },
        toString: function () {
            return [this.$className, "[", decodeURIComponent($.param(this.config).replace(/\&/g, ", ")), "]"].join(" ");
        }
    });

    firebird.info("Firebird.Service loaded.");

	module.exports = Firebird.Service;
});